#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<fstream>
#include<sstream>
#include<set>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
using std::ifstream;

class TextQuery
{
public:
    void readFile(const string& filename);
    void query(const string & word);
private:
    vector<string> _lines;
    std::map<string,std::set<int>> _WordNUmbers;
    std::map<string,int> _dict;
};

void TextQuery::readFile(const string & filename)
{
    ifstream ifs(filename);
    if(!ifs)
    {
        cout<<"打开文件失败"<<endl;
        return;
    }
    string line;
    //从文件流读每行
    int linen=0;
    _lines.reserve(10000);
    while(std::getline(ifs,line))
    {
        ++linen;
        _lines.push_back(line);
        std::istringstream iss(line);
        string word;
        while(iss>>word)
        {
            auto pi=word.begin();
            for(;pi<word.end();++pi)
            {
                if(!isalpha(*pi))
                {
                    word.erase(pi);
                }
            }
            if(word.size()==0)
            {
                continue;
            }
            _WordNUmbers[word].insert(linen);
            auto res=_dict.insert({word,1});
            if(!res.second)
            {
                ++_dict[word];

            }
        }
    }
        ifs.close();
}
    void TextQuery::query(const string & word)
{
    cout<<"-------------------------------------------------"<<endl;
    cout<<word<<" occurs "<<_dict[word]<<" times."<<endl;
    auto i=_WordNUmbers[word].begin();
    int k=0;
    for(;i!=_WordNUmbers[word].end();++i)
    {
        ++k;
        cout<<"(line "<<*i<<")"<< _lines[*i-1]<<endl;
        if(k==6)
            break;
    }
    cout<<"-------------------------------------------------"<<endl;
}
int main(void)
{
    string filename;
    cout<<"请输入文件名字"<<endl;
    cin>>filename;
    TextQuery qt ;
    qt.readFile(filename);
    string queryword;
    cout<<"请输入要查找的单词"<<endl;
    cin>>queryword;
    qt.query(queryword);
}
